<template>
    <div
        class="page_root"
        :key="queryUpdateFlag"
        data-page-name="自动化脚本配置"
        data-page-identification="p_1ljn98dplg"
    >
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_z6a2k56r8w 自定义模板_gmcfrl5jko -->
            <!--          新建/编辑脚本-->
            <a-modal
                centered
                :visible="state.modalVisible"
                :title="state.modalTitle"
                @cancel="cancelModal"
                @ok="submitData"
                :mask-closable="false"
                :keyboard="false"
                width="1000px"
                destroy-on-close
                :body-style="{
                    maxHeight: '800px',
                    overflowY: 'auto'
                }"
                :ok-button-props="{ loading: state.modalLoading }"
            >
                <div class="form-div">
                    <a-form :model="state.modalForm" ref="formRef" :rules="rules">
                        <a-row>
                            <a-col :span="24">
                                <a-form-item label="类型" name="type">
                                    <a-select
                                        :placeholder="selectHolder"
                                        v-model:value="state.modalForm.type"
                                        :options="state.typeList"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="编码" name="code">
                                    <a-input
                                        :disabled="currentData.id"
                                        v-model:value="state.modalForm.code"
                                        :placeholder="inputHolder"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="名称" name="name">
                                    <a-input v-model:value="state.modalForm.name" :placeholder="inputHolder" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="参数格式">
                                    <a-textarea
                                        :rows="4"
                                        v-model:value="state.modalForm.repParams"
                                        :placeholder="inputHolder"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="参数描述">
                                    <a-textarea
                                        :rows="4"
                                        v-model:value="state.modalForm.comment"
                                        :placeholder="inputHolder"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item label="提示词" name="cueWord">
                                    <a-textarea
                                        :rows="4"
                                        v-model:value="state.modalForm.cueWord"
                                        :placeholder="inputHolder"
                                    />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
            </a-modal>
            <!--          新建/编辑脚本-->
            <div class="body">
                <div class="top-search">
                    <a-row>
                        <a-col :span="5">
                            <a-form-item label="名称" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
                                <a-input
                                    :placeholder="inputHolder"
                                    v-model:value="state.filter.name"
                                    @change="debounceData"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="5">
                            <a-form-item label="类型" :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }">
                                <a-select
                                    :placeholder="selectHolder"
                                    v-model:value="state.filter.type"
                                    :options="state.typeList"
                                    @change="getData"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="2" offset="12" style="display: flex; justify-content: end">
                            <a-button type="primary" ghost @click="resetData"> 重置</a-button>
                        </a-col>
                    </a-row>
                </div>
                <div class="content">
                    <div class="table-top">
                        <div class="tip">自动化脚本列表</div>
                        <a-space>
                            <a-button type="primary" class="import-btn radius4" @click="handleAdd"> 新建</a-button>
                        </a-space>
                    </div>
                    <div class="table-box">
                        <a-table
                            bordered
                            :columns="columns"
                            :data-source="state.dataSource"
                            :loading="state.tableLoading"
                            :pagination="false"
                            :scroll="{ y: state.tableHeight }"
                        >
                            <template #bodyCell="{ column, record, text }">
                                <template v-if="column.dataIndex === 'opration'">
                                    <a-button size="small" type="link" @click="handleEdit(record)">编辑 </a-button>

                                    <a-popconfirm
                                        title="确定删除吗?"
                                        ok-text="确定"
                                        cancel-text="取消"
                                        @confirm="handleDelete(record.id)"
                                        @cancel="cancel"
                                    >
                                        <a-button size="small" type="link">删除 </a-button>
                                    </a-popconfirm>
                                </template>
                            </template>
                        </a-table>
                    </div>
                </div>
            </div>
            <!-- end vid_z6a2k56r8w 自定义模板_gmcfrl5jko -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    onMounted(() => {
        getTypeList()
        getData()
    })
    const inputHolder = '请输入'
    const selectHolder = '请选择'
    const state = reactive({
        filter: {
            name: undefined,
            type: undefined
        },
        typeList: [],
        tableLoading: false,
        dataSource: [],
        modalForm: {
            code: undefined,
            name: undefined,
            type: undefined,
          repParams: undefined,
            comment: undefined,
            cueWord: undefined,
            template: ` date＝{
          "start_time": "2025-07-07 00:00:00", //说明:非必填
          "end_time": "2025-07-07 00:00:00", //说明:非必填
          "file": "永登点位清单_202507070010.xlsx",  //说明:非必填,无文件默认""。文件点位清单首行:点位清单
          "table_name": "1d，1h（默认）",　//说明:非必填,当前只能选择【 1d，1h】
          "line_filter": "1＝2＝3，all（默认）",　//说明:非必填,【＝作为分隔符】 all为执行全部
          }`
        },
        modalVisible: false,
        modalTitle: '',
        modalLoading: false,
        tableHeight: 600
    })
    const rules = computed(() => ({
        name: [{ required: true, message: '请输入名称', trigger: ['blur', 'change'] }],
        type: [{ required: true, message: '请选择类型', trigger: ['blur', 'change'] }],
        code: [{ required: true, message: '请输入编码', trigger: ['blur', 'change'] }],
        cueWord: [
            {
                required: state.modalForm.type === 'COMPONENT', // 会动态计算
                message: '请输入提示词',
                trigger: ['blur', 'change']
            }
        ]
    }))
    const columns = ref([
        {
            title: '类型',
            dataIndex: 'typeName',
            align: 'center',
            ellipsis: true
        },
        {
            title: '编码',
            dataIndex: 'code',
            align: 'center',
            ellipsis: true
        },
        {
            title: '名称',
            dataIndex: 'name',
            align: 'center',
            ellipsis: true
        },
        {
            title: '参数格式',
            dataIndex: 'repParams',
            align: 'center',
            ellipsis: true
        },
        {
            title: '参数描述',
            dataIndex: 'comment',
            align: 'center',
            ellipsis: true
        },
        {
            title: '提示词',
            dataIndex: 'cueWord',
            align: 'center',
            ellipsis: true
        },
        {
            title: '操作',
            width: 140,
            align: 'center',
            dataIndex: 'opration'
        }
    ])
    function getTypeList() {
        get(' /solution-ppm-basic-data/api/v1/dictionary/search/JCSJ.DSFMJ').then(data => {
            state.typeList = data.data.map(item => {
                return {
                    label: item.itemName,
                    value: item.itemCode
                }
            })
        })
    }
    function handleAdd() {
        ;(state.modalTitle = '新建脚本'), (state.modalVisible = true)
    }
    // 页面里直接手写防抖
    function debounce(fn, delay = 500) {
        let timer = null
        const debounced = function (...args) {
            clearTimeout(timer)
            timer = setTimeout(() => {
                fn.apply(this, args)
            }, delay)
        }
        debounced.cancel = () => {
            clearTimeout(timer)
            timer = null
        }
        return debounced
    }

    // 创建防抖后的请求函数
    const debounceData = debounce(() => {
        getData()
    }, 500)
    function getData() {
        state.tableLoading = true
        post('/solution-ppm/api/v2/base_data/third_enumeration/search', state.filter)
            .then(data => {
                state.dataSource = data.data
            })
            .finally(() => {
                state.tableLoading = false
            })
    }
    function resetData() {
        state.filter.type = state.filter.name = undefined
        getData()
    }
    const formRef = ref(null)
    const currentData = ref({})
    function submitData() {
        formRef.value.validate().then(() => {
            const api = currentData.value.id ? put : post
            state.modalLoading = true
            api('/solution-ppm/api/v2/base_data/third_enumeration', state.modalForm)
                .then(data => {
                    if (data.code !== 200) {
                        message.error(data.message)
                        return
                    }
                    message.success(data.message)
                    cancelModal()
                    getData()
                })
                .finally(() => {
                    state.modalLoading = false
                })
        })
    }
    function cancelModal() {
        state.modalVisible = false
        state.modalForm = {
            name: undefined,
            code: undefined,
            type: undefined,
            comment: undefined,
            repParams: undefined,
            cueWord: undefined
        }
        currentData.value = {}
    }
    function handleEdit(record) {
        currentData.value = record
        Object.assign(state.modalForm, record)
        state.modalTitle = '编辑脚本'
        state.modalVisible = true
    }
    function handleDelete(id) {
        del(`/solution-ppm/api/v2/base_data/third_enumeration/${id}`).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            message.success(data.message)
            getData()
        })
    }
    const headerOffset = ref(170)
    const calcTableHeight = () => {
        state.tableHeight = window.innerHeight - 150 - headerOffset.value
    }
    onMounted(() => {
        calcTableHeight()
        window.addEventListener('resize', calcTableHeight)
    })

    onBeforeUnmount(() => {
        window.removeEventListener('resize', calcTableHeight)
    })
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    .body {
        height: 100%;
    }
    .top-search {
        background-color: #fff;
        padding: 16px 16px 0 16px;
    }
    .content {
        padding: 16px 24px;
        background-color: #fff;
        margin-top: 16px;
        height: 100%;
    }
    .table-top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 16px;
    }
    .tip {
        font-size: 16px;
        color: #262626;
        letter-spacing: 0;
        font-weight: 600;
        line-height: 16px;
        border-left: 4px solid #3875ff;
        padding-left: 4px;
        height: 16px;
    }
    .form-div :deep(.ant3-form-item-label) {
        width: 80px;
    }
    .table-box :deep(.@{ant-prefix}-table-thead) > tr > th {
        background: #3875ff;
        color: #fff;
        font-weight: 600;
        padding: 8px 16px;
        border-right: 1px solid #d9d9d9 !important;
        position: relative;
    }
    .table-box :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-family: arial, helvetica, 'microsoft yahei';
        font-weight: 400;
        color: #262626;
        border-bottom: 1px solid #d9d9d9;
        padding: 8px 16px;
        word-break: break-all;
    }
</style>
